package countHillValley;

public class Solution {
    public int countHillValley(int[] nums) {
        int ans = 0;
        for (int i = 1; i < nums.length-1; i++) {
            int next = checkHill(nums,i);
            if(next!=-1) {
                ans++;
                i = next;
            }else if((next = checkValley(nums,i))!=-1) {
                ans++;
                i = next;
            }
        }
        return ans;
    }
    private int checkHill(int[] nums,int i) {
        int n = nums.length;
        int j = i-1;
        while (j>=0&&nums[j]==nums[i])j--;
        if(j<0||nums[j]>nums[i])return -1;
        j = i+1;
        while (j<n&&nums[j]==nums[i])j++;
        if(j>=n||nums[j]>nums[i])return -1;
        return j;
    }
    // 返回下一个
    private int checkValley(int[] nums,int i) {
        int n = nums.length;
        int j = i-1;
        while (j>=0&&nums[j]==nums[i])j--;
        if(j<0||nums[j]<nums[i])return -1;
        j = i+1;
        while (j<n&&nums[j]==nums[i])j++;
        if(j>=n||nums[j]<nums[i])return -1;
        return j;
    }
}
